package com.mlm.mlmapp.activity;

import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.DimensionRes;
import org.androidannotations.annotations.res.DrawableRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.activity.layoutmanager.SyGridLayoutManager;
import com.mlm.mlmapp.adapter.view.GridMarginDecoration;
import com.mlm.mlmapp.animation.RecyclAnimation;
import com.mlm.mlmapp.cons.HTTPCons;
import com.mlm.mlmapp.interfaces.Prefs_;
import com.mlm.mlmapp.utils.CommonUtils;

@EActivity(R.layout.coupon_get)
public class CouponGetListActivity extends BaseActivity implements HTTPCons {

	@Pref
	Prefs_ pref;
	@DimensionRes(R.dimen.recyclerview_mycomments_space)
	float commentImagesMargin;
	@DimensionRes
	float comments_images_edge;
	@ColorRes
	int red;
	@ColorRes
	int lightgreytext;
	@ColorRes
	int blacktext;
	@ViewById
	TextView tv_title;
	@ViewById
	TextView tv_no_title;
	private AQuery aq;
	private CouponListAdapter adapter;
	List<JSONObject> couponListDataset;
	@ViewById
	RecyclerView rv_coupons;
	@Extra
	String couponid;
	@Extra
	String id;
	@DrawableRes
	Drawable grey_edge_btn_long;
	@OnActivityResult(REQUEST_CODE)
	void onResult(Intent data) {
		if (data != null) {
			if (data.getBooleanExtra("flag", false)) {
				init();
			} else {
				this.finish();
			}
		}
	}
	@AfterViews
	public void init() {
		String title=getTitle().toString();
		if(!"".equals(title)){
			((TextView) this.findViewById(R.id.tv_title)).setText(title);
		}
		
		if ("0".equals(pref.loginID().get())) {
			LoginActivity_.intent(this).startForResult(REQUEST_CODE);
			return;
		}
		aq = new AQuery(this);
		aq.hardwareAccelerated11();
		couponListDataset = new ArrayList<>();
		final GridLayoutManager layoutManager = new SyGridLayoutManager(this, 1);
		rv_coupons.setLayoutManager(layoutManager);
		rv_coupons
				.addItemDecoration(new GridMarginDecoration(this, 0, 0, 0, 0));
		rv_coupons.setItemAnimator(new RecyclAnimation());
		adapter = new CouponListAdapter(CouponGetListActivity.this,
				couponListDataset);
		ImageView iv = (ImageView)findViewById(R.id.iv_default);
		TextView t = (TextView)findViewById(R.id.tv_content);
		iv.setImageResource(R.drawable.noitem_coupon);
		t.setText("暂无优惠券信息");
		rv_coupons.setAdapter(adapter);
		getCouponAction();

	}

	void getCouponAction() {
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		pairs.add(new BasicNameValuePair("mobile", pref.loginID().get()));
		CommonUtils.postRequest4Array(get_coupon, aq,
				new AjaxCallback<JSONArray>() {

					@Override
					public void callback(String url, JSONArray array,
							AjaxStatus status) {
						Log.d("sort", "callback: "+array.toString());
						if (status.getCode() == -101) {
							Toast.makeText(aq.getContext(), "网络异常,请检查网络",
									Toast.LENGTH_SHORT);
							return;
						}
						// TODO Auto-generated method stub
						if (status.getCode() == 200) {

							for (int i = 0; i < array.length(); i++) {
								JSONObject obj;
								try {
									obj = array.getJSONObject(i);
									couponListDataset.add(obj);
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

							}
							if (couponListDataset.size() > 0) {
								rv_coupons.setVisibility(View.VISIBLE);
							} else {
								rv_coupons.setVisibility(View.INVISIBLE);
							}
							rv_coupons.getAdapter().notifyDataSetChanged();

						} else if (status.getCode() == 500) {
							Toast.makeText(aq.getContext(),
									"服务器异常:" + status.getCode() ,
									Toast.LENGTH_LONG).show();
						} else {
							Toast.makeText(aq.getContext(),
									"网络异常:" + status.getCode(),
									Toast.LENGTH_LONG).show();

						}
					}

				}, pairs);
	}

	class CouponListAdapter extends
			RecyclerView.Adapter<RecyclerView.ViewHolder> {
		private Context mContext;
		private List<JSONObject> array;
		private List<RadioButton> rlist;

		public CouponListAdapter(Context con, List<JSONObject> array) {
			this.mContext = con;
			this.array = array;
			rlist = new ArrayList<RadioButton>();

		}

		@Override
		public int getItemCount() {
			return array.size();
		}

		public boolean isPositionHeader(int position) {
			return position == 0;
		}

		@Override
		public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
				int viewType) {
			// TODO Auto-generated method stub
			final CouponViewHolder holder = new CouponViewHolder(LayoutInflater
					.from(CouponGetListActivity.this).inflate(
							R.layout.coupon_get_list_item, parent, false));
			return holder;

		}

		private void radioGroupChecked(CompoundButton buttonView) {
			for (RadioButton rb : rlist) {
				if ((int) rb.getTag() != (int) buttonView.getTag()) {
					rb.setChecked(false);
				}

			}
		}

		@Override
		public void onBindViewHolder(RecyclerView.ViewHolder holder,
				int position) {
			// TODO Auto-generated method stub
			final CouponViewHolder vholder = (CouponViewHolder) holder;
			final JSONObject temp = array.get(position);
			vholder.tv_name.setText(getJsonString(temp, "couponName"));
			vholder.btn_get.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					List<NameValuePair> pairs = new ArrayList<NameValuePair>();
					pairs.add(new BasicNameValuePair("mobile", pref.loginID()
							.get()));
					pairs.add(new BasicNameValuePair("couponId", getJsonString(
							temp, "id")));
					CommonUtils.postRequest(obtain_coupon, aq,
							new AjaxCallback<JSONObject>() {

								@Override
								public void callback(String url,
										JSONObject temp, AjaxStatus status) {

									if (status.getCode() == -101) {
										Toast.makeText(aq.getContext(),
												"网络异常,请检查网络",
												Toast.LENGTH_SHORT);
										return;
									}
									// TODO Auto-generated method stub
									if (status.getCode() != 200) {
										Toast.makeText(aq.getContext(),
												"服务器异常:" + status.getCode(),
												Toast.LENGTH_LONG).show();
									} else {
										Toast.makeText(aq.getContext(),
												"操作结果:" + temp.toString(),
												Toast.LENGTH_LONG).show();
									}
								}

							}, pairs);
				}
			});

			if (getJsonInt(temp, "isReceive") != 0) {

				disabledStyle(vholder);
			}
		}

		private void disabledStyle(CouponViewHolder holder) {
			holder.tv_name.setTextColor(lightgreytext);
			holder.btn_get.setText("已领取");
			holder.btn_get.setTextColor(lightgreytext);
			holder.btn_get.setBackground(grey_edge_btn_long);
			holder.btn_get.setEnabled(false);
		}

		public class CouponViewHolder extends RecyclerView.ViewHolder {
			TextView tv_name;
			Button btn_get;

			public CouponViewHolder(View itemView) {
				super(itemView);
				this.tv_name = (TextView) itemView.findViewById(R.id.tv_name);
				this.btn_get = (Button) itemView.findViewById(R.id.btn_get);
			}
		}
	}

	@Click
	void btn_back() {
		onBackPressed();
	}

	

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		Intent data = new Intent();
		setResult(RESULT_CANCELED, data);
		this.finish();
	}

}
